//
//  FileManager.m
//  SqliteManagerDemo
//
//  Created by 曾威林 on 2017/9/14.
//  Copyright © 2017年 US bike. All rights reserved.
//

#import "FileManager.h"

#define FILE_PATH @"device_id.csv"
#define DOCUMENT_PATH NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]

@implementation FileManager

//加载文件中的数据
+ (void) loadFileDataWithBlock:(void(^)(NSArray<DeviceItem *> * items)) loadBlock {
    
    
    NSString *filePath = [DOCUMENT_PATH stringByAppendingPathComponent:FILE_PATH];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    
    NSError *error;

    if (![manager fileExistsAtPath:filePath]) {
        NSString *originFilePath = [[NSBundle mainBundle] pathForResource:@"device_id" ofType:@"csv"];
        
        [manager copyItemAtPath:originFilePath toPath:filePath error:&error];
        if (error) {
            NSLog(@"文件copy失败，%@",error);
            return;
        }
    }
    
    
    NSString *dataStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"读取文件失败,%@",error);
        return;
    }
    
    dataStr = [dataStr stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    
    
    
    NSArray<NSString *> *strArray = [dataStr componentsSeparatedByString:@"\n"];
    
    NSMutableArray<DeviceItem *> *itemsArray = [NSMutableArray array];
    for (NSString *temp in strArray) {
        DeviceItem *item = [[DeviceItem alloc] initWithStr:temp];
        [itemsArray addObject:item];
    }

    if (loadBlock) {
        loadBlock(itemsArray);
    }
}

//把数据保存到文件中
+ (void) saveFileWithArray:(NSArray<DeviceItem *> *) items WithBlock:(void(^)()) saveBlock {

    NSMutableString *dataStr = [NSMutableString string];
    
    for (DeviceItem *item in items) {
        NSString *itemStr = [item dataStr];
        
        [dataStr appendString:itemStr];
        [dataStr appendString:@"\n"];
    }
    
    NSError *error;
    NSString *filePath = [DOCUMENT_PATH stringByAppendingPathComponent:FILE_PATH];
    bool succed = [dataStr writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    
    if (succed) {
        NSLog(@"数据保存成功");
    } else {
        NSLog(@"数据保存失败,%@", error);
        return;
    }
    
    if (saveBlock) {
        saveBlock();
    }
    
}



@end
